package com.yungu.swift.socket.communication.server.handler.strategy;

import com.google.gson.Gson;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.SpringContextHolder;
import com.yungu.swift.socket.communication.message.UploadLocationMessage;
import com.yungu.swift.socket.communication.message.UploadLocationResponseMessage;
import com.yungu.swift.socket.communication.service.UploadLocationService;
import com.yungu.swift.socket.component.ChannelKeeper;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * 上传位置响应
 *
 * @author : cuixiuyin
 * @date : 2019/8/30
 */
@Slf4j
public class UploadLocationHandler implements MessageHandler {

    @Override
    public void handler(ChannelHandlerContext channelHandlerContext, String text) {
        UploadLocationService uploadLocationService = SpringContextHolder.getBean(UploadLocationService.class);
        Gson gson = new Gson();
        //将报文转换成可保存的实体
        UploadLocationMessage uploadLocationMessage = gson.fromJson(text, UploadLocationMessage.class);
        //上传位置信息时，再主动刷新一次通道
        log.info("上传位置信息报文创建推送通道 netty client success:uuid-->{}", uploadLocationMessage.getClientUuid());
        ChannelKeeper.removeByUuid(uploadLocationMessage.getClientUuid());
        ChannelKeeper.add(uploadLocationMessage.getClientUuid(), channelHandlerContext.channel());
        //处理业务逻辑
        ResponseData<Map<String, Object>> uploadResult = uploadLocationService.uploadDriverLocation(uploadLocationMessage);
        UploadLocationResponseMessage uploadLocationResponseMessage;
        if (uploadResult.isSuccess() && uploadResult.getData() != null) {
            Map<String, Object> map = uploadResult.getData();
            uploadLocationResponseMessage = new UploadLocationResponseMessage(uploadLocationMessage.getLocationUuid(), (Double) map.get("totalFare"), true, "上传成功");
        } else {
            uploadLocationResponseMessage = new UploadLocationResponseMessage(uploadLocationMessage.getLocationUuid(), null, false, "上传失败");
        }
        uploadLocationResponseMessage.setClientUuid(uploadLocationMessage.getClientUuid());
        uploadLocationResponseMessage.setOrderUuid(uploadLocationMessage.getOrderUuid());
        //给响应客户端响应处理结果
        channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(gson.toJson(uploadLocationResponseMessage)));
    }
}
